package com.tiyende.credit.loop.ui.activity

import android.graphics.Color
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import com.tiyende.credit.loop.R
import com.tiyende.credit.loop.common.CommonActivity
import com.tiyende.credit.loop.databinding.TiyendeActivityProfileBinding
import com.tiyende.credit.loop.event.TiyendeEventPointType
import com.tiyende.credit.loop.event.TiyendeEventData
import com.tiyende.credit.loop.ui.contract.IViewContract
import com.tiyende.credit.loop.ui.presenter.TiyendeImageUploadPresenter
import com.tiyende.credit.loop.utils.TiyendeImageUtil
import com.tiyende.credit.loop.utils.helper.TiyendeCustomDataHelper
import com.tiyende.credit.loop.utils.imgcovert.ImageConvert
import com.tiyende.credit.loop.utils.log.TiyendeLogger

/**
 * TiyendeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/28 18:11
 * @Annotation：个人信息
 */
class TiyendeProfileActivity: CommonActivity(), IViewContract.ITiyendeImageUploadView {
    lateinit var binding: TiyendeActivityProfileBinding
    private var presenter: TiyendeImageUploadPresenter? = null

    //图片选择
    lateinit var pickMedia: ActivityResultLauncher<PickVisualMediaRequest>

    override fun getTiyendeRootView(): View {
        binding = TiyendeActivityProfileBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initTiyendeView() {
        setTiyendeTitleBarVisibility(View.VISIBLE)
        setTiyendeTextTitle(getString(R.string.tiyende_user_center_profile))
        setTiyendeTextTitleColor(Color.parseColor("#FFFFFF"))
        setTiyendeRightBtnRes(R.mipmap.tiyende_customer_white)
        setTiyendeBackBtnRes(R.mipmap.tiyende_back_white)
    }

    override fun initTiyendeListener() {
        //客服
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog("Profile Page")
            addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_CUSTOMER,"Profile Page")
            if (binding.editUserName.isFocused){
                binding.editUserName.clearFocus()
            }
        }
        binding.parentLayout.setOnClickListener {
            if (binding.editUserName.isFocused){
                binding.editUserName.clearFocus()
            }
        }
        binding.imgUserPicture.setOnClickListener {
            if (binding.editUserName.isFocused){
                binding.editUserName.clearFocus()
            }
            openUserInfoAlbum()
        }
        //昵称
        binding.editUserName.setOnFocusChangeListener { v, hasFocus ->
            when(hasFocus){
                true -> {//获得焦点
                }
                else -> {//失去焦点
                    val userName = binding.editUserName.text.toString().trim()
                    if (userName.isNotEmpty()){
                        TiyendeCustomDataHelper.saveTiyendeCustomUserNameAction(userName)
                    }
                }
            }
        }

        binding.editUserName.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                binding.editUserName.clearFocus()
                true
            }
            false
        }

        // 1-注册图库组件
        pickMedia = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
            if (uri != null) {
                // 图片处理
                ImageConvert.covert(context = this, uri = uri) { localPath, bitmap ->
                    if (localPath != null){
                        TiyendeLogger.e(">>>>>>>album>>>>>>>>>>$localPath")
                        showTiyendeLoading(isTOuchOut = false, isCancel = false)
                        presenter?.submitUploadImageAction(localPath)
                    }
                }
            } else {
                TiyendeLogger.e("No media selected")
            }
        }
    }

    override fun loadTiyendeData() {
        setUserInfoData()
    }

    /**
     * 设置用户信息
     */
    private fun setUserInfoData(){
        val avatarUrl = TiyendeCustomDataHelper.queryTiyendeCustomUserAvatarUrl()
        if (avatarUrl.isNotEmpty()){
            TiyendeImageUtil.instance?.loadImageUrl(this,binding.imgUserPicture,avatarUrl)
        } else {
            binding.imgUserPicture.setImageResource(R.mipmap.tiyende_holder)
        }
        binding.editUserName.setText(TiyendeCustomDataHelper.queryTiyendeCustomUserName())
    }

    /**
     * 打开相册
     */
    private fun openUserInfoAlbum(){
        if (presenter == null){
            presenter = TiyendeImageUploadPresenter(this)
        }
        pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
    }

    /**
     * 图片上传成功
     */
    override fun showTiyendeImageUploadSuccess(imgPath: String, imgUrl: String) {
        TiyendeCustomDataHelper.saveTiyendeCustomUserAvatar(imgUrl)
    }

    override fun onTiyendePublishEvent(event: TiyendeEventData) {
        super.onTiyendePublishEvent(event)
        when(event.eventType){
            TiyendeEventData.TYPE.TIYENDE_CUSTOM_DATA_REFRESHED -> {//自定义数据刷新完成
                //设置用户昵称和头像
                setUserInfoData()
            }
            else -> {

            }
        }
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(TiyendeEventPointType.PAGE.TIYENDE_PAGE_USER_INFORMATION_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(TiyendeEventPointType.PAGE.TIYENDE_PAGE_USER_INFORMATION_END)
    }
}